package com.example.demo.common.msg;/**
 * Created by kete on 2017-12-18.
 */

import com.alibaba.fastjson.JSONObject;
import com.example.demo.common.msg.disruptor.MessageSendConfig;
import com.example.demo.common.msg.service.EmailService;
import com.example.demo.common.persistence.dao.MsgRecordMapper;
import com.example.demo.common.persistence.model.MsgRecord;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

import javax.jms.Message;
import javax.jms.TextMessage;
import java.util.Map;

/**
 * 作者：kete
 * 创建时间：2017-12-18 10:52
 * 功能描述：
 * 版本：
 */
@Component
@ConditionalOnProperty(prefix = "guns", name = " mq-open", havingValue = "true")
public class MsgListener {

    @Autowired
    private MsgRecordMapper msgRecordMapper;

    /**
     * 消息消费成功，更新消息投递状态
     * @param recordId
     */
    private void updateMsgRecordDeliveryState(String recordId){
        try {
            if (StringUtils.isNotEmpty(recordId)) {
                MsgRecord update = new MsgRecord();
                update.setId(new Integer(recordId));
                update.setMsgStatus("1");

                msgRecordMapper.updateById(update);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @JmsListener(containerFactory = "jmsListenerContainerFactory", destination = MessageSendConfig.emailQueue)
    public void msgCustomer(Message message){

        try {
            Map<String, String> messageBody = JSONObject.parseObject(((TextMessage) message).getText(), Map.class);
            String msgId = messageBody.get("msgId");

            String email = messageBody.get("email");
            String title = messageBody.get("title");
            String content = messageBody.get("content");
            String configType = messageBody.get("configType");
            boolean isSuccess = EmailService.sendMail(email, title, content, "", configType);
            if (isSuccess) {
                updateMsgRecordDeliveryState(msgId);
                message.acknowledge();
            }
            //todo 记录消费结果
        } catch (Throwable e) {
            e.printStackTrace();
        }

    }

}
